package com.superwein.springcloud.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.superwein.springcloud.gateway.domain.AjaxResult;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;

/**
 * 网关鉴权
 */
// @Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static Map<String, String> map = new HashMap<>();

    /**
     * 程序启动的时候加载权限的信息，比如从文件、数据库中加载
     */
    static {
        map.put("jack", "123456");
    }

    /**
     * 简单判断
     *
     * @param name
     * @param password
     * @return
     */
    public static boolean isPermitted(String name, String password) {
        return map.containsKey(name) && map.get(name).equals(password);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取header的参数
        String name = exchange.getRequest().getHeaders().getFirst("username");
        String password = exchange.getRequest().getHeaders().getFirst("password");
        // 权限比较
        boolean permitted = isPermitted(name, password);
        if (permitted) {
            return chain.filter(exchange);
        } else {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return exchange.getResponse().writeWith(
                    Mono.just(response.bufferFactory().
                            wrap(JSON.toJSONBytes(AjaxResult.fail(
                                    HttpStatus.UNAUTHORIZED.value(), "没有访问权限")))));
            /*exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();*/
        }
    }

    @Override
    public int getOrder() {
        return -90;
    }

}
